//
//  NSTimer+QSExtension.m
//  KetogenicDietitan
//
//  Created by Apple on 2018/10/9.
//  Copyright © 2018年 Ketogenic. All rights reserved.
//

#import "NSTimer+QSExtension.h"

/** 定时器block关联key */
static NSString *TimerOperationBlockKey = @"TimerOperationBlockKey";

@implementation NSTimer (QSExtension)
/**
 *  创建定时器
 *
 *  @param time 时间间隔
 *  @param timerOperationBlock 定时器到时回调block
 *  return 返回实例
 */
+ (instancetype)qs_createTimerWithTimeInterval:(NSTimeInterval)time timerOperation:(TimerOperationBlock)timerOperationBlock
{
    objc_setAssociatedObject(self, &TimerOperationBlockKey, timerOperationBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:time
                                     target:self
                                     selector:@selector(myTimerOperation:)
                                   userInfo:nil
                                    repeats:YES];
    
    // 添加到运行时循环
    NSRunLoop *mainLoop = [NSRunLoop mainRunLoop];
    [mainLoop addTimer:timer forMode:NSRunLoopCommonModes];
    
    return timer;
}

/**
 *  定时器到时
 */
+ (void)myTimerOperation:(NSTimer *)timer
{
    TimerOperationBlock block = objc_getAssociatedObject(self, &TimerOperationBlockKey);
    if (block) {
        block(timer);
    }
}

/**
 *  永远停止定时器
 */
- (void)qs_invalidateTimer
{
    [self invalidate];
}

/**
 *  停止定时器
 */
- (void)qs_stopTimer
{
    [self setFireDate:[NSDate distantFuture]];
}

/**
 *  重新开启定时器
 */
- (void)qs_fireTimer
{
    [self setFireDate:[NSDate distantPast]];
}

/**
 *  开启定时器，并设置定时时间
 */
- (void)qs_fireTimerWithTimeInterval:(NSTimeInterval)timeInterval
{
    [self setFireDate:[NSDate dateWithTimeIntervalSinceNow:timeInterval]];
}
@end
